package br.com.jk.financeiro.movimentotipo;

import br.com.jk.financeiro.movimentotipo.MovimentoTipo.Tipo;
import br.com.jk.util.Util;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author camilo
 */
public class MovimentoTipoJDialog extends javax.swing.JDialog {

  private static MovimentoTipoJDialog dialog;
  // Model da tabela
  MovimentoTipoTableModel movTipoTm = new MovimentoTipoTableModel();
  MovimentoTipoController control = new MovimentoTipoController();
//  atributos utilizados nas pesquisas externas
  private JTextField idPesquisa;
  private JTextField descricaoPesquisa;
  private static MovimentoTipo movimentoTipoPesquisa;
  private boolean modoConsultaExt;

  public static MovimentoTipoJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (dialog == null) {
      dialog = new MovimentoTipoJDialog(parent, modal);
    }
    return dialog;
  }

  public static MovimentoTipoJDialog getInstance(java.awt.Frame parent, boolean modal, MovimentoTipo movTipo) {
    if (dialog == null) {
      dialog = new MovimentoTipoJDialog(parent, modal, movTipo);
    }
    return dialog;
  }

  /**
   * Creates new form FornecedorJDialog
   */
  private MovimentoTipoJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    init();
  }

  private MovimentoTipoJDialog(java.awt.Frame parent, boolean modal, MovimentoTipo movTipo) {
    super(parent, modal);
    MovimentoTipoJDialog.movimentoTipoPesquisa = movTipo;
    this.modoConsultaExt = true;

    initComponents();
    init();
  }

  private void init() {
    criaModel();

    setLocationRelativeTo(null);
    listar();
    jlFiltro.setVisible(false);
  }

  private void criaModel() {
    jtMovimentoTipo.setModel(movTipoTm);

    movTipoTm.sorter(jtMovimentoTipo, movTipoTm);

    /*jtProduto.getColumnModel().getColumn(ProdutoTableModel.COLUNA_COD_ID).setPreferredWidth(60);
     jtProduto.getColumnModel().getColumn(ProdutoTableModel.COLUNA_COD_DESCRICAO).setPreferredWidth(245);
     jtProduto.getColumnModel().getColumn(ProdutoTableModel.COLUNA_COD_NOME_UF).setPreferredWidth(40);*/
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do
   * NOT modify this code. The content of this method is always regenerated by the Form
   * Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    jbBuscar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtMovimentoTipo = new javax.swing.JTable();
    jpDados = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    jtfId = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jtfDescricao = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jcbxEntity = new javax.swing.JCheckBox();
    jcbxCheque = new javax.swing.JCheckBox();
    jcbxPrevision = new javax.swing.JCheckBox();
    jcbxNumber = new javax.swing.JCheckBox();
    jcbTipo = new javax.swing.JComboBox();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Tipos de movimento bancário");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    jbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    jbBuscar.setToolTipText("Buscar");
    jbBuscar.setEnabled(false);
    jbBuscar.setFocusable(false);
    jbBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbBuscar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbBuscarActionPerformed(evt);
      }
    });
    JtbMaster.add(jbBuscar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    JtbMaster.add(jlFiltro);
    JtbMaster.add(jSeparator2);

    /*jtMovimentoTipo.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtMovimentoTipo.getSelectedRow();
        fControl.selecionado();
      }
    });

    jtMovimentoTipo.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtMovimentoTipo.getSelectedColumn();
        fControl.selecionado();
      }
    });*/
    jtMovimentoTipo.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtMovimentoTipo.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtMovimentoTipoMouseClicked(evt);
      }
    });
    jtMovimentoTipo.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtMovimentoTipoKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtMovimentoTipoKeyReleased(evt);
      }
    });
    jScrollPane1.setViewportView(jtMovimentoTipo);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Dados"));
    java.awt.GridBagLayout jpDadosLayout = new java.awt.GridBagLayout();
    jpDadosLayout.columnWidths = new int[] {100, 50, 100};
    jpDados.setLayout(jpDadosLayout);

    jLabel2.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel2.setText("Id");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel2, gridBagConstraints);

    jtfId.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfId.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfId, gridBagConstraints);

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel3.setText("Descrição");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(14, 0, 0, 0);
    jpDados.add(jLabel3, gridBagConstraints);

    jtfDescricao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDescricao.setEnabled(false);
    jtfDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfDescricaoKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtfDescricaoKeyReleased(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfDescricao, gridBagConstraints);

    jLabel4.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel4.setText("Tipo");
    jLabel4.setToolTipText("Data Cadastro");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel4, gridBagConstraints);

    jcbxEntity.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbxEntity.setText("Exige Entidade");
    jcbxEntity.setEnabled(false);
    jcbxEntity.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbxEntityKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jcbxEntity, gridBagConstraints);

    jcbxCheque.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbxCheque.setText("Cheque");
    jcbxCheque.setEnabled(false);
    jcbxCheque.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbxChequeKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    gridBagConstraints.insets = new java.awt.Insets(14, 0, 0, 0);
    jpDados.add(jcbxCheque, gridBagConstraints);

    jcbxPrevision.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbxPrevision.setText("Exige Previsão");
    jcbxPrevision.setEnabled(false);
    jcbxPrevision.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbxPrevisionKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jcbxPrevision, gridBagConstraints);

    jcbxNumber.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbxNumber.setText("Exige Nº Documento");
    jcbxNumber.setEnabled(false);
    jcbxNumber.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbxNumberKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jcbxNumber, gridBagConstraints);

    jcbTipo.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbTipo.setEnabled(false);
    jcbTipo.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbTipoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jcbTipo, gridBagConstraints);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGap(4, 4, 4)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jpDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)))
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(13, 13, 13))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed
    pesquisar();
  }//GEN-LAST:event_jbBuscarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
//      Master.setJpbStatusIndeterminate(true);
//      Master.setTextJlStatus("Gerando relatório...");
      ThreadReport thReport = new ThreadReport();
      thReport.start();

    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    listar();
    jlFiltro.setVisible(false);
    jbBuscar.setEnabled(false);
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtMovimentoTipoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtMovimentoTipoMouseClicked
    if (movTipoTm.getRowCount() > 0 && (jtfId.getText() != null && jtfDescricao != null)) {
      selecionado();
    }
  }//GEN-LAST:event_jtMovimentoTipoMouseClicked

  private void jtfDescricaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDescricaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      salvar();
    }
  }//GEN-LAST:event_jtfDescricaoKeyPressed

  private void jtMovimentoTipoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtMovimentoTipoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (jbBuscar.isEnabled()) {
        pesquisar();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        selecionaRegistro();
      }
    }
  }//GEN-LAST:event_jtMovimentoTipoKeyPressed

  private void jtfDescricaoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDescricaoKeyReleased
    Util.setFirstLetterUpperCase(jtfDescricao, jtfDescricao.getSelectionStart());
  }//GEN-LAST:event_jtfDescricaoKeyReleased

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    dialog = null;
  }//GEN-LAST:event_formWindowClosed

  private void jtMovimentoTipoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtMovimentoTipoKeyReleased
    if (evt.getKeyCode() == KeyEvent.VK_UP
            || evt.getKeyCode() == KeyEvent.VK_DOWN
            || evt.getKeyCode() == KeyEvent.VK_LEFT
            || evt.getKeyCode() == KeyEvent.VK_RIGHT) {
      selecionado();
    }
  }//GEN-LAST:event_jtMovimentoTipoKeyReleased

  private void jcbTipoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbTipoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jcbxCheque.requestFocus();
    }
  }//GEN-LAST:event_jcbTipoKeyPressed

  private void jcbxChequeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbxChequeKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jcbxNumber.requestFocus();
    }
  }//GEN-LAST:event_jcbxChequeKeyPressed

  private void jcbxNumberKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbxNumberKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jcbxEntity.requestFocus();
    }
  }//GEN-LAST:event_jcbxNumberKeyPressed

  private void jcbxEntityKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbxEntityKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jcbxPrevision.requestFocus();
    }
  }//GEN-LAST:event_jcbxEntityKeyPressed

  private void jcbxPrevisionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbxPrevisionKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfDescricao.requestFocus();
    }
  }//GEN-LAST:event_jcbxPrevisionKeyPressed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(MovimentoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(MovimentoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(MovimentoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(MovimentoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        MovimentoTipoJDialog dialog = new MovimentoTipoJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JButton jbBuscar;
  private javax.swing.JComboBox jcbTipo;
  private javax.swing.JCheckBox jcbxCheque;
  private javax.swing.JCheckBox jcbxEntity;
  private javax.swing.JCheckBox jcbxNumber;
  private javax.swing.JCheckBox jcbxPrevision;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpDados;
  private javax.swing.JTable jtMovimentoTipo;
  private javax.swing.JTextField jtfDescricao;
  private javax.swing.JTextField jtfId;
  // End of variables declaration//GEN-END:variables

  public void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);

    jcbTipo.requestFocus();
  }

  private void getLarguraJtBanco() {
    int grade;
    int column = movTipoTm.getColumnCount();
    //JtBanco.getColumnModel().getSelectedColumnCount();
    for (int i = 0; i < column; i++) {
      grade = this.jtMovimentoTipo.getColumnModel().getColumn(i).getPreferredWidth();
      System.out.println(grade);
    }
  }

  private void getPositionColumns() {
    System.out.println(jtMovimentoTipo.getColumnModel().getColumn(0).getHeaderValue());
  }

  public void selecionado() {
    habilitaJb(true, false, true, false, true);
    habilitaJtf(false);
    limpar();

    int linha = jtMovimentoTipo.getSelectedRow();//grava a linha selecionada
    int linhaSel = jtMovimentoTipo.convertRowIndexToModel(linha);

    if (linhaSel >= 0) { // executa o procedimento se o JTable não estiver vazio
      int colunaSel = jtMovimentoTipo.getSelectedColumn(); //grava a coluna selecionada
      boolean pesq = control.setEnabledPesquisa(colunaSel); // Verifica as colunas que serão habilitadas para pesquisa
      jtfId.setText(movTipoTm.getValueAt(linhaSel, MovimentoTipoTableModel.COLUNA_COD_ID).toString());
      jcbTipo.getModel().setSelectedItem(movTipoTm.getValueAt(linhaSel, MovimentoTipoTableModel.COLUNA_COD_TIPO));
      jcbxCheque.setSelected(Boolean.parseBoolean(movTipoTm.getValueAt(linhaSel, MovimentoTipoTableModel.COLUNA_COD_IS_CHEQUE).toString()));
      jcbxEntity.setSelected(Boolean.parseBoolean(movTipoTm.getValueAt(linhaSel, MovimentoTipoTableModel.COLUNA_COD_REQUEST_ENTITY).toString()));
      jcbxNumber.setSelected(Boolean.parseBoolean(movTipoTm.getValueAt(linhaSel, MovimentoTipoTableModel.COLUNA_COD_REQUEST_NUMBER).toString()));
      jcbxPrevision.setSelected(Boolean.parseBoolean(movTipoTm.getValueAt(linhaSel, MovimentoTipoTableModel.COLUNA_COD_REQUEST_PREVISION).toString()));

      control.modoConsulta = pesq;
      jbBuscar.setEnabled(pesq);
    }
  }

  public MovimentoTipo criaObjeto() {
    MovimentoTipo movimentoTipo = new MovimentoTipo();
    movimentoTipo.setDescricao(jtfDescricao.getText());
    movimentoTipo.setIsCheque(jcbxCheque.isSelected());
    movimentoTipo.setRequestEntity(jcbxEntity.isSelected());
    movimentoTipo.setRequestNumber(jcbxNumber.isSelected());
    movimentoTipo.setRequestPrevision(jcbxPrevision.isSelected());
    movimentoTipo.setTipo(Tipo.valueOf(jcbTipo.getModel().getSelectedItem().toString()));
    if (!jtfId.getText().isEmpty()) {
      movimentoTipo.setId(Integer.parseInt(jtfId.getText()));
    }
    return movimentoTipo;
  }

  private void salvar() {
    control.salvar(criaObjeto());
    listar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    limpar();
  }

  private void listar() {
    setJtBancoTm(control.listar());
    limpar();
    listarTipo();
    System.out.println(movTipoTm.getRowCount());
    if (movTipoTm.getRowCount() > 0) {
      jtMovimentoTipo.setRowSelectionInterval(0, 0);
      selecionado();
    }
  }

  private void limpar() {
    jcbxCheque.setSelected(false);
    jcbxEntity.setSelected(false);
    jcbxNumber.setSelected(false);
    jcbxPrevision.setSelected(false);
    jtfDescricao.setText(null);
    jtfId.setText(null);
    jbBuscar.setEnabled(false);
  }

  public void setJtBancoTm(List<MovimentoTipo> ct) {
    removeAllJtable();
    if (!ct.isEmpty()) {
      movTipoTm.adicionaLista(ct);
    }
  }

  public void setJtCotacaoTm(MovimentoTipo ct) {
    removeAllJtable();
    if (ct != null) {
      movTipoTm.adiciona(ct);
    }
  }

  private void removeAllJtable() {
    while (movTipoTm.getRowCount() > 0) {
      movTipoTm.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  public void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  public void habilitaJtf(Boolean tf) {
    jcbxCheque.setEnabled(tf);
    jtfDescricao.setEnabled(tf);
    jcbxEntity.setEnabled(tf);
    jcbTipo.setEnabled(tf);
    jcbxNumber.setEnabled(tf);
    jcbxPrevision.setEnabled(tf);
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jcbTipo.requestFocus();
  }

  private void excluir() {
    control.excluir(criaObjeto());
    listar();
    limpar();
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    if (control.modoConsulta) {
      control.modoConsulta = false;
    } else {
      listar();
    }
  }

  public static MovimentoTipo getMovimentoTipoPesquisa() {
    MovimentoTipoJDialog.getInstance(null, true);
    dialog.modoConsultaExt = true;
    dialog.setVisible(true);
    return movimentoTipoPesquisa;
  }

  private void selecionaRegistro() {
    movimentoTipoPesquisa = criaObjeto();
    modoConsultaExt = false;
    this.dispose();
  }

  private void pesquisar() {
    setJtBancoTm(control.pesquisar());
    jlFiltro.setVisible(true);
    jbBuscar.setEnabled(false);
    limpar();
  }

  private void listarTipo() {
    jcbTipo.removeAllItems();
    for (Tipo tipo : Tipo.values()) {
      jcbTipo.addItem(tipo);
    }
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        control.report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }
}
